<%@ page language="java" pageEncoding="UTF-8" import="ll.sms.pojo.ChannelCombox,ll.sms.util.*"%>
<%@page import="java.util.List;"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>代理信息修改</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
		<link rel="stylesheet" type="text/css" href="../ext/ext-all.css" />
		<link rel="stylesheet" type="text/css" href="../ext/sms.css" />
		<script type="text/javascript" src="../ext/ext-base.js"></script>
		<script type="text/javascript" src="../ext/ext-all.js"></script>
	    <link rel="stylesheet" type="text/css" href="../myjs/multiselect.css"/>
	    <script type="text/javascript" src="../myjs/DDView.js"></script>
	    <script type="text/javascript" src="../myjs/MultiSelect.js"></script>
	    <script type="text/javascript" src="../myjs/ItemSelector.js"></script>
<style type="text/css">
.settings {
	background: url(../img/delete.gif) left top no-repeat !important;
	}
</style>

<%
List<ChannelCombox> list = SmsUtil.getChannelList();
%>


	<script type="text/javascript">

Ext.BLANK_IMAGE_URL = '../images/s.gif';

	Ext.apply(Ext.form.VTypes, {
	password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passwordText : '密码不匹配'
	});
	Ext.onReady(function(){

	var swin;//弹出window对象


    var wi = 600;


	// used to add records to the destination stores
	var thiswindow;
	function getchannleview(pid){
 	var conn = Ext.lib.Ajax.getConnectionObject().conn;
	conn.open("GET", '../ajaxjsp/proxy.jsp?pid='+pid+'&newflag='+new Date().getTime(),false);
	conn.send(null);
	var returnstr = conn.responseText.split('|');
	var tostr=returnstr[1];
	var fromstr=returnstr[0];
	//alert(tostr);
	//alert(fromstr);
	 	var t = [];
	 	var f = [];
	 	if(tostr != null ){
	 		if(Ext.isEmpty(tostr)){tostr='[]';}
	 		t = eval(tostr);

	 	}
	 	if(fromstr != null){
	 		if(Ext.isEmpty(fromstr)){fromstr='[]';}
	 		f = eval(fromstr);

	 	}
		var isForm = new Ext.form.FormPanel({
        //title: 'ItemSelector Test',
        //width:700,
        //regin
        bodyStyle: 'padding:10px;',
        //renderTo: 'itemselector',
        items:[{
            xtype:"itemselector",
            name:"itemselector",
            fieldLabel:"为该代理配置通道",
            dataFields:["code", "desc"],
			toData: t,
            msWidth:250,
            msHeight:200,
            valueField:"code",
            displayField:"desc",
            imagePath:"../images/",
            toLegend:"已配置通道",
            fromLegend:"未配置通道",
            //fromData:returnstr[0],
            fromData : f,
            toTBar:[{
                text:"重置",
                handler:function(){
                    var i=isForm.getForm().findField("itemselector");
                    i.reset.call(i);
                }
            }]
        }],

        buttons: [{
            text: '确定',
            handler: function(){
                if(isForm.getForm().isValid()){
                   doset(isForm.getForm().getValues(true));
                   thiswindow.hide();
                }
            }
        }]
    });

	 thiswindow =new Ext.Window({
	    title    : '通道配置',
		width    : 800,
		height   : 400,
		layout   : 'fit',
		//applyTo : 'panel123',
		closeAction :'hide',
		items    : [
			isForm
		]
	});

	return thiswindow
	}

	var showproxy;
	function creatorshowproxy(pid){
	showproxy =new Ext.Button({
	        // applyTo:'login-button-group',
	         text: '配置代理',

	         handler: function()
		         {
		         	//creatorOneGrid();
		         	//creatorTwoGrid();
		         	//creatorWindowView();
					//displayPanel.show();

					getchannleview(pid);

		         	thiswindow.show();
		         }
		     	});
		     	return showproxy;
		}
//****************************************************************
//****************************************************************
//****************************************************************
	var store1 = new Ext.data.SimpleStore({
	fields: ['clazz', 'showname'],
	data : <%=ExtJsonBuilder.channel2ArrayStringNoAll(list)%>
	});

	var simple;

    var comb = new Ext.form.ComboBox({
            emptyText : '请选择',
            store: store1,
            mode:'local',
            triggerAction:'all',
            valueField: 'clazz',
            name:'_adefaultchannel_',
            id:'_adefaultchannel_',
            hiddenName : 'adefaultchannel_',
            displayField:'showname',
 			fieldLabel: '重选通道',
 			 width : 120
            });

		var thisgrid;
	//---定义修改form

	function creatorSimpleForm(pid){
	    creatorshowproxy(pid);

		simple = new Ext.FormPanel({
        labelWidth: 100, // label settings here cascade unless overridden
        url:'../ajaxjsp/proxyeditor.jsp',
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',
        items: [
        	{
                fieldLabel: 'id',
                name: 'aid',
                xtype:'hidden'
            },
           {
                fieldLabel: '管理员用户名',
                name: 'auname',
                allowBlank:false,
                blankText :'管理员用户名必须填写'
            },{
                fieldLabel: '密码',
                name: 'apwd',
                vtype:'alphanum',
               //inputType : 'password',
                vtypeText:'密码只能包括字母或者数字',
                allowBlank:false,
                id:'apwd',
                blankText :'密码必须填写'
            },{
                fieldLabel: '代理公司名',
                name: 'acompany',
                allowBlank:false,
                blankText :'代理公司名必须填写'
            },{
                fieldLabel: '公司地址',
                name: 'aaddress'
            },{
                fieldLabel: '公司电话',
                name: 'aphone'
            },{
                fieldLabel: '联系人',
                name: 'alinkman',
                allowBlank:false,
                blankText :'联系人必须填写'
            },{
                fieldLabel: '联系人电话',
                name: 'alinkmanphone',
                allowBlank:false,
                blankText :'联系人电话必须填写'
            },
             {
                fieldLabel: '注册日期',
                  xtype:'hidden',
                name: 'aregisttime'
            },
            {
                fieldLabel: '联系人QQ',
                 xtype:'numberfield',
                name: 'alinkmanqq'
            },
            {
                fieldLabel: '可发短信数',
                name: 'asmsnum',
                xtype:'numberfield',
                allowBlank:false,
                blankText :'可发短信数必须填写'
            },{
                fieldLabel: '是否可用',
                name: 'aavailable',
                xtype:'hidden'
            },{
                fieldLabel: '已配置代理',
                name: 'adefaultchannel',
                id : 'adefaultchannel',
                xtype:'hidden'
            },showproxy
            ],
            buttons: [{
            text: '修改',
            handler : function(){
            //alert(Ext.get('checkbox').getValue());

           	var v = simple.getForm().findField('adefaultchannel').getValue();
			if(Ext.isEmpty(v)){
			Ext.MessageBox.confirm('警告', '你没有对代理配置通道，你确定不配置通道?',dosetchannel);
			}else{

			dosubmit();
			}

			function dosetchannel(btn){
				if(btn=='yes'){
					dosubmit();
				}else{
					displayPanel.show();
				}
			}

			function dosubmit(){
			 simple.form.submit({

					waitMsg : '正在处理......',
					success : function(form, action) {
					    try{swin.close();}catch(e){}
						Ext.Msg.alert('成功','>>>>'+action.result.msg+'<<<<');
						doreset();
					},
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);
							}else{
							Ext.MessageBox.alert('错误','--------非法输入-------');
							}
					}
				});
			}

            }
        }]
    });
    return simple;
	}

    //form end
//aaddress,aphone,alinkman,alinkmanphone,alinkmanqq
    var sm = new Ext.grid.CheckboxSelectionModel();
    sm.handleMouseDown = Ext.emptyFn;

	var AdminRecord = Ext.data.Record.create([
        {name: 'aid', type: 'string'},
        {name: 'auname', type: 'string'},
        {name: 'apwd', type: 'string'},
        {name: 'acompany', type: 'string'},
        {name: 'aregisttime', type: 'string'},
        {name: 'arank', type: 'int'},
        {name: 'asmsnum', type: 'int'},
        {name: 'aavailable', type: 'int'},
            {name: 'aaddress', type: 'string'},
            {name: 'aphone', type: 'string'},
            {name: 'alinkman', type: 'string'},
            {name: 'alinkmanphone', type: 'string'},
            {name: 'alinkmanqq', type: 'string'},
            {name: 'adefaultchannel', type: 'string'}

    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/proxtlist.jsp'}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },AdminRecord),
        remoteSort: true
    });

    function avi(value){
		if(value==0){
			return '是';
			}else if(value==-1){
			return '否';
			}else{
			return 'N/A';
			}
        }

    var columns = new Ext.grid.ColumnModel([
        //{header: '编号', dataIndex: 'aid',width:1},
        new Ext.grid.RowNumberer(),
        sm,
        {header:'充值记录',dataIndex:"chargelist",width:70,align:'center',renderer:cbutton},
        {header: '用户名', dataIndex: 'auname',renderer:aunames},
        {header: '公司名称', dataIndex: 'acompany'},
        //{header: '注册日期', dataIndex: 'aregisttime'},
        {header: '可用余额', dataIndex: 'asmsnum'},
        {header: '充值',dataIndex:"chargeme",width:70,align:'center',renderer:cmbutton},
        {header: '修改密码',dataIndex:"changepwd",width:70,align:'center',renderer:cpbutton}
    ]);

	function aunames(value,c){
		return "<font style='color:red;text-decoration:underline;cursor:hand;font-color:red;'>"+value+"</font>";
	}
	function cbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值记录</button>";
	  return returnStr;
	}

	function cmbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值</button>";
	  return returnStr;
	}

	function cpbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>修改密码</button>";
	  return returnStr;
	}

//=充值

function getchargeForm(chargeedId,chargedUsername){
	var chargefield=new Ext.form.NumberField({
				fieldLabel: '充值金额',
                name: 'addcharge',
                //width : '80%',
                id:'addcharge',
                xtype :'NumberField',
                allowBlank:false,
                blankText :'金额必须填写'
				});

var chargeform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/charge.jsp?opflag=a&chargeedId='+chargeedId+'&chargedUsername='+chargedUsername,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [
            chargefield
            ],
            buttons: [{
            text: '充值',
            handler : function(){chargeform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {
					    doreset();
						Ext.Msg.alert('成功',action.result.msg);
						try{swin.close();}catch(e){}
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
            });
            return chargeform;
}


//*************

function getchangepwdForm(userid){
var pwdform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/proxyeditor.jsp?flag=changepassword&userid='+userid,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [

             {
                fieldLabel: '新密码',
                //width : '80%',
                name :'pwd',
                allowBlank:false,
                blankText :'密码必须填写'
            },{
                fieldLabel: '重复新密码',
                //width : '80%',
                name :'npwd',
                allowBlank:false,
                blankText :'密码必须填写'
            }

            ],
            buttons: [{
            text: '修改',
            handler : function(){
            pwdform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {

						try{swin.close();}catch(e){}
						Ext.Msg.alert('成功','>>>>'+action.result.msg+'<<<<');
						doreset();
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
    });
       return pwdform;
}

//*************************
//获得充值列表
function getChargeListGrid(pid){

var ChargeRecord = Ext.data.Record.create([
        {name: 'cid', type: 'string'},
        {name: 'cuname', type: 'string'},
        {name: 'cprice', type: 'string'},
        {name: 'csmsnum', type: 'string'},
        {name: 'ctime', type: 'string'},
        {name: 'coperator', type: 'string'},
        {name: 'cnote', type: 'string'}


    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/chargelist.jsp?pid='+pid}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },ChargeRecord),
        remoteSort: true
    });


    var columns = new Ext.grid.ColumnModel([
        //{header: '编号', dataIndex: 'aid',width:1},
        new Ext.grid.RowNumberer(),
        //{header: '被充值者', dataIndex: 'cuname'},
        {header: '充值', dataIndex: 'csmsnum'},
        {header: '充值时间', dataIndex: 'ctime'},
        {header: '操作员', dataIndex: 'coperator'}
        //{header: '通道密码', dataIndex: 'hpwd'}
    ]);

        columns.defaultSortable = true;
        var grid = new Ext.grid.GridPanel({
        loadMask: true,
        store: store,
        cm: columns,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        })
    });

    store.load({params:{start:0,limit:15}});

    return grid;

}

function showmywindow(obj,t,w,h){
	var tw;
	var th;

	if(w==undefined){
		tw = 500;
	}else{
		tw = w;
	}
	if(h==undefined){
		th = 300;
	}else{
		th = h;
	}

	 swin = new Ext.Window({
		title : t,
		width    : tw,
		height   : th,
		layout   : 'fit',
		//applyTo : 'panel123',
		closeAction :'close',
		items    : [obj],
		bbar    : [
			'->',
			{
			text    : '关闭',
			handler : function() {
					if(thiswindow){
					thiswindow.close();
					}
					swin.close();

				}
			}

		]
	});
	return swin;
	}


    columns.defaultSortable = true;

  var _grid_ = new Ext.grid.EditorGridPanel({
        title: '代理列表',
        region: 'center',
        loadMask: true,
        store: store,
        cm: columns,
        sm: sm,
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        }),
        tbar: new Ext.Toolbar({
        items:[
        '-',
               {
                    id:'del'
                    ,iconCls:'settings'
                    ,text:"删除"
                    ,handler: function(){
                    doGrid();
                    }
                },
'-'
            ]
        })
    });

    store.load({params:{start:0,limit:15}});
    /*
    grid.on('rowclick',function (grid,rowIndex,event){
    var record = grid.getStore().getAt(rowIndex);
   	simple.getForm().loadRecord(record);
    });
   */
	thisgrid =_grid_;

    _grid_.on('cellclick',function (ngrid, rowIndex, columnIndex, e){
    var record = ngrid.getStore().getAt(rowIndex);   //Get the Record
    var fieldName = ngrid.getColumnModel().getDataIndex(columnIndex); //Get field name

   	if(fieldName == 'auname'){
   	var w = showmywindow(creatorSimpleForm(record.get('aid')),'信息修改',500,400);
   	w.show();
	simple.getForm().loadRecord(record);
   	}

   	if(fieldName == 'chargelist'){
   	var w =showmywindow(getChargeListGrid(record.get('auname')),record.get('acompany')+'充值历史');
   	w.show();
   	}

   	if(fieldName == 'chargeme'){
   	var w =showmywindow(getchargeForm(record.get('aid'),record.get('auname')),'充值',300,150);
   	w.show();
   	}

   	if(fieldName == 'changepwd'){
   	var w =showmywindow(getchangepwdForm(record.get('aid')),'更改密码',300,200);
   	w.show();
   	}
    //var data = record.get('aid');
    //alert(data);
    //Ext.MessageBox.alert('show','当前选中的数据是'+data);
    });

	window.onload = function (){
	var viewport = new Ext.Viewport({
	renderTo:Ext.getBody(),
	layout:'border',
	items:[
	_grid_,
	//simple,
	{region:'south',contentEl:'inp',heigth:40}
	//{region:'east',html:'east',width:'30%'}
	]
	});
	}

 /*
    function doset(){
	var store = secondGrid.getStore();
	var count = store.getCount();
	var value='';
	for(var i = 0 ; i<count ;i++){
		value = value + store.getAt(i).get('name');
		if(i!=count-1){
		value = value+',';
		}
	}
	simple.getForm().findField('adefaultchannel').setValue(value);
	displayPanel.close();
	}
*/

	function doset(value){
	simple.getForm().findField('adefaultchannel').setValue(value);
	thiswindow.hide();
	}
	function doreset(){
		_grid_.getStore().reload();
	}

	function doGrid(){
        var rows = thisgrid.getSelectionModel().getSelections();
        if (rows.length == 0) {
            Ext.MessageBox.alert('错误', '最少选择一条信息，进行操作!');
        }
        else {
       		var names='';
                    for (var i = 0; i < rows.length; i++) {
                        names=names+rows[i].get('acompany')+',';
                    }
            Ext.MessageBox.confirm('警告', '您确定要进行代理删除操作吗？<br>即将删除的代理为【'+names+'】<br>该删除将会删除如下说明：<br><br>1、删除该代理。<br>2、删除属于该代理下的所有用户。<br>3、删除该代理下的所有业务员。<br>4、删除业务员与用户的级联信息。<br>5、属于该代理用户的已经发送的消息以及在等待发送的消息将不会被删除。', function(btn){
                if (btn == 'yes') {
                var delid='';
                    for (var i = 0; i < rows.length; i++) {
                        delid=delid+rows[i].get('aid')+'^';
                    }
                 Ext.Ajax.request({
                  url : '../ajaxjsp/system.jsp?flag=delproxy',
                  method : 'POST',
                  params : {
                      delid : delid
                  },
                  success: function(response, options) {
                        //获取响应的json字符串
                       var responseArray = Ext.util.JSON.decode(response.responseText);
                            if(responseArray.success==true){
                            	 Ext.Msg.alert('成功','操作成功');
								thisgrid.getStore().reload();
                            }
                            else{
                                Ext.Msg.alert('失败','删除操作失败');
                            }
                         }
              });
                }
            });
        }
    }

});


	</script>
  </head>

  <body>
   <div id="mt"></div>
   <div id="north1"></div>
   <div id="south"></div>

   <div id = "panel123"></div>

   <div id="chargelist"></div>
   <div id="chargeme"></div>
   <div id="changepwd"></div>
   <div id="wait" align="center"></div>
   <input id="inp" value="刷新页面" type="button" onclick="javascript:window.location.reload();"></input>
  </body>
</html>
